//
//  RmoveBgViewController.swift
//  Matting
//  Created by JoyWT on 2022/3/10
//  
    

import UIKit
import EasyPeasy
import opencv2
import EasyPeasy
import RxCocoa
import RxSwift
class RmoveBgViewController: AlphaViewController {
    let disposeBag = DisposeBag()
    var alpha:UIImage?
    let slider = UISlider().then {
        $0.minimumValue = 10
        $0.maximumValue = 255
        $0.value = 75

    }
    let filteSizeLable = UILabel().then {
        $0.textAlignment = .center
        $0.textColor = .black
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(slider)
        view.addSubview(filteSizeLable)
        slider.easy.layout(
            Width(200),Height(50),Top(10).to(filteSizeLable, .bottom),CenterX())
        filteSizeLable.easy.layout(Top(110),CenterX())
        slider.rx.value.asObservable().subscribe(onNext:{
            [weak self] v in
               self?.filteSizeLable.text = "过滤阀值: \(Int(v))"
            self?.sliderChange()
        }).disposed(by: disposeBag)
//        test2()
    }
    
    override func pickedDone() {
        let md = Mat(uiImage: maskImage!) //deaplab生成的mask图 ,黑色为前景区域
        //处理背景图片
        let nmd = Mat()
        Core.bitwise_not(src: md, dst: nmd) //对mask图片取反 白色为前景区域

        let trimap = trimap(mask: nmd, shape: .MORPH_CROSS, ksize: Size2i(width: 3 , height: 3))
        let orgin = originalImage!
         alpha = alpha(orgin: orgin, trimap: trimap.toUIImage())
//        let orgin = UIImage(named: "plant.jpg")
//         alpha = alpha(orgin: orgin!, trimap: UIImage(named: "plant.png")!)
        if alpha == nil {return}
        let matting = removeBg(origin: orgin, alpha: alpha!)
        imageView.image = matting
        
    }
    func test(){
        //处理背景图片
//        let orgin = originalImage!
//        let alpha = alpha(orgin: orgin, trimap: trimap.toUIImage())
        let orgin = UIImage(named: "plant.jpg")
        alpha = alpha(orgin: orgin!, trimap: UIImage(named: "plant.png")!)
        if alpha == nil {return}
        let matting = removeBg(origin: orgin!, alpha: alpha!)
        imageView.image = matting
    }
    func sliderChange(){
        if alpha == nil {return}
        let orgin = originalImage!

        let matting = removeBg(origin: orgin, alpha: alpha!)
        imageView.image = matting
    }
    func removeBg(origin:UIImage , alpha: UIImage)-> UIImage{
        let od = Mat(uiImage: origin)
        let md = Mat(uiImage: alpha)
        let cd = Mat(rows: od.rows(), cols: od.cols(), type: od.type(), scalar: Scalar(0))
//        print(cd.total())
        let cdp = cd.dataPointer()
        let odp = od.dataPointer()
        let mdp = md.dataPointer()
//        print(od.channels())
//        print(od.total())
//
//        print(md.channels())
//        print(md.total())
        let rgb = Int(od.channels())
        //方向运算
        /*
        for i in 0...od.total(){
            if mdp[Int(i)] <= 30 {
                for wi in 0...Int(rgb) {
                    let index = i*Int(rgb) + wi
                    odp[index] = 0 //设置255和0都是白色,不知道原因,只有128附近的值才会显示
                }
            }

        }*/
        let contours = findContours(mask: md)
        let w = md.width()
    
        for i in 0...od.total(){
            let intI = Int(i)
            if mdp[intI] > Int(slider.value) {
                let p = Point2f(x: Float(intI % Int(w)), y: Float(intI / Int(w)))
                if isInside(contours: contours, point: p) {
                    for wi in 0...rgb {
                        let index = i*rgb + wi
                        cdp[index] =  odp[index]
                    }
                }
            }
        }

        return cd.toUIImage()
    }
    func test2(){
//        COLOR_BGR2GRAY
        let d = Mat(uiImage: UIImage(named: "23.png")!)
        let dd = Mat()
        d.convert(to: dd, rtype: 6)
        print(dd.type())
        let contours = findContours(mask: dd)
        print(isInside(contours: contours, point: Point2f(x: 0.0, y: 0.0)))

    }
    func isInside(contours:NSMutableArray, point: Point2f ) -> Bool{
        var flag =  -1
        for contour in contours {
            flag = Int(Imgproc.pointPolygonTest(contour: contour as! [Point2f] , pt: point, measureDist: false))
            if flag == 1 {
                break
            }
        }
        return flag == 1
        
    }
    func findContours(mask: Mat)->NSMutableArray{
        let contours:NSMutableArray = NSMutableArray()
        let h = Mat()
        Imgproc.findContours(image:mask , contours: contours, hierarchy: h, mode: .RETR_TREE, method:.CHAIN_APPROX_SIMPLE )
        return contours
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
